package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

//获得老师上传的头像并保存
@WebServlet("/upload_teacherImg")
@MultipartConfig
public class upload_teacherImg extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset = utf-8");
        request.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();

        Part filePart = request.getPart("img");
        String id = request.getParameter("id");
        String fileName = id + ".jpg";

        // 指定上传目录，这里使用绝对路径或ServletContext的相对路径
        String uploadDir1 = request.getServletContext().getRealPath("") + java.io.File.separator + "userImg" + java.io.File.separator;
        String uploadDir2 = "D:\\code\\2024\\Project\\StuddentManager\\web\\userImg";
        java.io.File file1 = new java.io.File(uploadDir1 + File.separator + fileName);
        java.io.File file2 = new java.io.File(uploadDir2 + File.separator + fileName);
        try {
            //上传文件
            InputStream fileContent = filePart.getInputStream();
            Files.copy(fileContent, file1.toPath(), StandardCopyOption.REPLACE_EXISTING);
            fileContent = filePart.getInputStream();
            Files.copy(fileContent, file2.toPath(), StandardCopyOption.REPLACE_EXISTING);
            out.print("<script>alert('上传成功!');window.location.href='teacher/personal.jsp';</script>");
            fileContent.close();
        }
        catch (Exception e){
            out.print("上传失败："+ e);
        }
    }

}
